package cn.com.wxd.servlet;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.biz.website.WebsiteCache;
import cn.com.wxd.plugin.baiduueditor.GenerateConfigJson;
import cn.com.wxd.service.attach.AttachUtil;
import cn.com.wxd.service.dispatch.engine.QuartzEngine;
import cn.com.wxd.service.javamail.MailInfo;
import cn.com.wxd.service.javamail.MailSender;
import cn.com.wxd.service.keyword.KeyWordFilter;
import cn.com.wxd.service.permissions.core.PermissionsCore;
import cn.com.wxd.service.permissions.core.RoleCore;
import cn.com.wxd.service.sms.SmsInfo;
import cn.com.wxd.service.sms.SmsSentFactor;
import cn.com.wxd.service.weather.WeatherService;
import cn.com.wxd.common.DateUtil;
import cn.com.wxd.util.action.AccessLogUtil;
import cn.com.wxd.util.dao.JdbcUtil;
import cn.com.wxd.util.service.ProjectInfo;
import cn.com.wxd.common.system.SystemInfoUtil;
import cn.com.wxd.util.user.UserUtil;
import cn.com.wxd.util.website.WebsiteInfo;

/**
 * Title:初始化应用servlet
 * Description:cn.com.wxd.servlet
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2015-10-27 下午4:17:05
 *
 * @author WangXuDong
 * @version 1.0
 */
public class Initialization extends HttpServlet {
    /**
     *
     */
    private static final long serialVersionUID = -6880678394657176536L;
    private static final Logger log = LoggerFactory.getLogger(Initialization.class);
    private static boolean isExitSystem = false;

    public void init() throws ServletException {
        log.info("#########################项目开始初始化！");
        Timer timeoutTimer = new Timer(true);
        timeoutTimer.schedule(new TimeoutTask(), 30000);  //30秒后没有初始化成功则认为失败,退出系统
        initProject();
        initUser();
        initWebsite();
        initService();
        initpPlugin();
        log.info("#########################系统初始化成功！");
        // 关闭计时器
        timeoutTimer.cancel();
    }

    /**
     * 初始化项目
     */
    private void initProject() {
        // 初始化
        log.info("开始初始化系统环境>>>>>>>>");
        log.info("IP地址：" + SystemInfoUtil.getHostAddress());
        log.info("操作系统(OS)：" + SystemInfoUtil.getOsName() + ",version:" + SystemInfoUtil.getOsVersion());
        log.info("机器名称：" + SystemInfoUtil.getmachineName() + "@" + SystemInfoUtil.getOsUserName());
        log.info("JAVA运行环境：java -version " + SystemInfoUtil.getJDKVersion());
        log.info("内存使用情况：(总大小)" + SystemInfoUtil.getMemeryInfo()[0] / 1024 + "MB,(使用率)" + SystemInfoUtil
                .getMemeryPercent());
        log.info("当前应用磁盘信息：");
        Map<String, String[]> map = SystemInfoUtil.getDisk();
        for (String key : map.keySet()) {
            log.info(key + ":使用空间:" + map.get(key)[3]);
        }
        log.info("初始化数据源");
        try {
            if (JdbcUtil.getJdbcTemplate() == null) {  //测试数据源及单例的srping持有类的加载情况
                log.error("初始化数据源失败，或SpringContext加载失败!");
                exitSystem();
            }
            log.info("spring持有类加载成功！");
            if (JdbcUtil.getJdbcTemplate().getDataSource().getConnection() == null) {
                log.error("初始化数据源失败！");
                exitSystem();
            }
            JdbcUtil.getJdbcTemplate().execute("SELECT 1");
        } catch (Exception e) {
            log.error("数据源初始化错误:" + e.getMessage(), e);
            exitSystem();
        }
        log.info("数据源连接成功!");
        log.info("环境初始化成功!");
        log.info("初始化项目信息>>>>>>>>");
        try {
            ServletContext application = getServletContext();
            application.setAttribute("ONLINECOUNT", 0);
            log.info(ProjectInfo.getProjectName());
        } catch (Exception e) {
            log.error("系统初始化失败!", e);
            exitSystem();
        }

        log.info(ProjectInfo.getCompanyName() + "," + ProjectInfo.getCopyright());
        log.info("版本信息:" + ProjectInfo.getVersion());
        log.info("主体初始化成功！");
        log.info("其他系统初始化开始>>>>>>>");

    }

    /**
     * 初始化用户系统
     */
    private void initUser() {
        //初始化用户表 第一次使用初始化超级管理员
        try {
            log.info("《用户系统》开始初始化" + ProjectInfo.getCopyright());
            log.info("用户权限和角色框架初始化！");
            try {
                PermissionsCore.getInstance();
                RoleCore.getInstance();
            } catch (Exception e) {
                log.error("初始化权限管理框架错误!");
                throw e;
            }
            log.info("Done");
            if (UserUtil.getUserCount() == 0) {
                log.info("第一次使用此系统请初始化管理员用户！");
                exitSystem();
            }
            UserUtil.initSystemAdminPermissions();
            log.info("Done");
            int count = UserUtil.getUserCount();
            if (count == -1) {
                log.error("初始化用户错误!");
                throw new Exception("用户初始化错误!");
            }
            log.info("用户数量为：" + count);
            log.info("总访问量截止" + DateUtil.getDatetimeStr() + ",统计为:" + AccessLogUtil.getTatorAccessVolume());
            log.info("用户初始化成功!");
        } catch (Exception e) {
            log.error("系统初始化失败!", e);
            exitSystem();
        }
    }

    /**
     * 初始化网站系统
     */
    private void initWebsite() {
        //网站初始化
        log.info("《" + WebsiteInfo.getWebsiteName() + "》网站开始初始化," + ProjectInfo.getCopyright());
        try {
            if (WebsiteInfo.isCache()) {
                log.info("网站ehchche缓存开始初始化......");
                if (WebsiteInfo.getCacheMaxCount() <= 0) {
                    throw new Exception("缓存数量请配置大于0的值");
                }
                WebsiteCache.init();
                log.info("网站栏目数量为:" + WebsiteCache.getCatalog().size());
                log.info("栏目缓存最大文章数量设置为:" + WebsiteInfo.getCacheMaxCount());
                log.info("网站缓存初始化成功!");
            }
            log.info("网站初始化成功!");
        } catch (Exception e) {
            log.error("系统初始化失败!", e);
            exitSystem();
        }
    }

    /**
     * 初始化项目服务系统
     */
    private void initService() {
        log.info("开始初始化系统服务>>>>>>>");
        log.info("敏感字过滤服务初始化");
        //敏感字过滤服务初始化!
        try {
            KeyWordFilter.doFilter("");
            log.info("Done");
        } catch (Exception e) {
            log.warn("敏感字过滤服务初始化失败，你将无法使用敏感字过滤！");
            log.error("", e);
        }
        //天气预报服务初始化
        log.info("天气更新服务开始初始化");
        try {
            WeatherService.upDateWheather();
            log.info(DateUtil.getDateStr() + "天气更新成功!");
            log.info("Done");
        } catch (Exception e) {
            log.warn("天气服务更新失败！");
            log.error("", e);
        }
        //定时任务Quartz引擎开始初始化
        log.info("定时任务Quartz引擎开始初始化");
        try {
            QuartzEngine.getInstance();
            log.info(QuartzEngine.getInstance().getScheduleModels().size() + "个任务已经正常初始化!");
            log.info("Done");
        } catch (Exception e) {
            log.warn("定时任务Quartz引擎初始化失败!");
            log.error("", e);
        }
        //短信服务初始化
        log.info("短信平台服务开始初始化");
        if (ProjectInfo.isSysCheckSms()) {
            try {
                //验证短信验证码的余额
                int num = SmsSentFactor.getSenter().queryBalance();
                SmsInfo.setSmsBalance(num);
                log.info(SmsInfo.getDefaultService() + "短信余额为:" + num + " 条");
                if (num <= 50) {
                    log.warn("短信剩余条数太少！请及时充值!");
                }
                if (num <= 1) {
                    log.error("短信数量太少!请充值后重新启动系统!");
                    exitSystem();
                }
            } catch (Exception e) {
                log.error("短信功能验证失败!" + e.getMessage());
                exitSystem();
            }
        }
        log.info("Done");
        //电子邮件服务初始化
        if (ProjectInfo.isSysCheckEmail()) {
            try {
                //验证邮箱发信邮件是否登录成功
                MailSender ms = new MailSender();
                ms.send(MailInfo.getEmail(), "系统启动邮箱登录检测", "<h1>您好:</h1><p>您收到这份邮件是因为" +
                        "你的邮件作为本系统的默认发件邮件</p>" +
                        "<p>系统使用此邮件作为默认的发件邮箱，如果您不知情请联系本系统的管理员" +
                        "</p>" +
                        "<p>系统描述:" + ProjectInfo.getCompanyName()
                        + ProjectInfo.getCopyright()
                        + ProjectInfo.getVersion() + "</p>" +
                        "<p>联系方式:<br>手机:" + WebsiteInfo.getPhone() + "<br></p>" +
                        "<br>邮箱:" + WebsiteInfo.getEmail() + "<br>" +
                        "<br>QQ:" + WebsiteInfo.getQQ() + "<br>" +
                        "<br>");
                log.info("邮箱验证成功");
            } catch (Exception e) {
                log.error("邮箱功能验证失败!" + e.getMessage(), e);
                exitSystem();
            }
            log.info("Done");

        }
    }

    /**
     * 初始化一些组件和框架
     */
    private void initpPlugin() {
        //组件开始初始化
        log.info("开始初始化系统插件>>>>>>>");
        //初始化线程池
        //		try{
        //			ThreadPoolManager tpm = ThreadPoolManager.getSingleton();
        //			tpm.init();
        //			if(log.isInfoEnabled()){
        //				log.info("ThreadPool4j---Done");
        //			}
        //		}catch (Exception e){
        //			if(log.isErrorEnabled()){
        //				log.error("线程池ThreadPool4j组件初始化错误!",e);
        //			}
        //			exitSystem();
        //		}
        //初始化上传框架
        try {
            AttachUtil.instance();
            log.info("FileUpLoad---Done");
        } catch (Exception e) {
            log.error("上传框架初始化错误!", e);
            exitSystem();
        }
        //初始化ueditor1.4插件
        try {
            GenerateConfigJson.init();
            log.info("uditor1.4---Done");
        } catch (Exception e) {
            log.error("ueditor1.4插件初始化错误!", e);
            //TODO exitSystem();
        }
    }

    /**
     * 退出当前系统
     */
    private void exitSystem() {
        if (!isExitSystem) {
            isExitSystem = true;
            int times = 10;
            while (times > 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    if (log.isErrorEnabled()) {
                        log.error("", e);
                    }
                }
                log.warn(times + "秒后退出程序！");
                times--;
            }
            log.warn("系统退出！");
            System.exit(0);
        }
    }

    private class TimeoutTask extends TimerTask {
        @Override
        public void run() {
            log.warn("系统初始化超时！");
            exitSystem();
        }
    }

}
